package com.scpii.universal.struts.manage;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.scpii.universal.action.BaseAction;
import com.scpii.universal.dto.ExcelImpAttrMapping;
import com.scpii.universal.pns.service.UsersService;
import com.scpii.universal.service.ContentService;
import com.scpii.universal.util.ExcelHelper;
import com.scpii.universal.util.StreamUtil;

@Controller
@Scope("prototype")
public class ExcelImpAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File fileInput;
	private String fileInputFileName;
	private String fileInputContentType;
	private Integer intCateId;
	private Integer sheetNo;
	private Integer headRow;
	private ExcelImpAttrMapping excelImpAttrMapping;
	@Resource
	private ContentService contentService;
	@Resource
	private UsersService usersService;
	private static final String EXCEL_NO_FILE = "请选择excel文件！";
	private static final String EXCEL_NO_DATA = "没有可导入的数据！";
	private static final String EXCEL_NO_INPUT_ATTR = "excel中不包含你输入的字段";
	private static final String EXCEL_IMP_SUCCESS = "导入成功！";
	private static final String EXCEL_TOO_MUCH_DATA = "数据量过大，预计处理时间会超过30分钟，建议分次导入，每次不超过5000条！";
	private static final String EXCEL_REQUIRED_COLUMN = "为必须字段！";
	private static final String USER_NAME = "用户名";
	private static final String PASSWORD = "密码";
	private static List<String> requiredPros = null;
	private Map<String,Integer> columnsIndex;
	
	static{
		requiredPros = new ArrayList<String>();
		requiredPros.add(USER_NAME);
		requiredPros.add(PASSWORD);
	}

	public File getFileInput() {
		return fileInput;
	}

	public void setFileInput(File fileInput) {
		this.fileInput = fileInput;
	}

	public Integer getIntCateId() {
		return intCateId;
	}

	public void setIntCateId(Integer intCateId) {
		this.intCateId = intCateId;
	}

	public Integer getSheetNo() {
		return sheetNo;
	}

	public void setSheetNo(Integer sheetNo) {
		this.sheetNo = sheetNo;
	}

	public Integer getHeadRow() {
		return headRow;
	}

	public void setHeadRow(Integer headRow) {
		this.headRow = headRow;
	}

	public String getFileInputFileName() {
		return fileInputFileName;
	}

	public void setFileInputFileName(String fileInputFileName) {
		this.fileInputFileName = fileInputFileName;
	}

	public String getFileInputContentType() {
		return fileInputContentType;
	}

	public void setFileInputContentType(String fileInputContentType) {
		this.fileInputContentType = fileInputContentType;
	}

	public ExcelImpAttrMapping getExcelImpAttrMapping() {
		return excelImpAttrMapping;
	}

	public void setExcelImpAttrMapping(ExcelImpAttrMapping excelImpAttrMapping) {
		this.excelImpAttrMapping = excelImpAttrMapping;
	}
	
	public String goInit() {
		System.out.println(111);
		return SUCCESS;
	}
	
	public String impUsersFromExcel() throws IOException {
		if (fileInput == null || (!fileInputFileName.endsWith(ExcelHelper.XLS)
				&& !fileInputFileName.endsWith(ExcelHelper.XLSX))) {
			jsonOut(EXCEL_NO_FILE);
			return null;
		}
		List<String> contents = acceptExcel();
		if (contents == null || contents.size() <= 0) {
			jsonOut(EXCEL_NO_DATA);
			return null;
		}
		String validateInfo = validate(contents, requiredPros);
		if (!StringUtils.isBlank(validateInfo)) {
			jsonOut(validateInfo);
			return null;
		}
//		usersService.
		return null;
	}
	
	private String validate(List<String> contents,List<String> requiredPros) {
		String info = null;
		info = validateExcelHead(contents, requiredPros);
		if (info != null)
			return info;
		info = validateExcelData(contents, requiredPros);
		if (info != null)
			return info;
		return info;
	}
	
	private String validateExcelHead(List<String> contents,List<String> requiredPros) {
		String[] pros = contents.get(0).split(ExcelHelper.SEPARATOR);
		columnsIndex = new HashMap<String,Integer>(requiredPros.size());
		for (int i = 0; i < pros.length; i++) {
			for (int j = 0; j < requiredPros.size(); j++) {
				if(pros[i].equals(requiredPros.get(j))){
					columnsIndex.put(requiredPros.get(j), i);
					requiredPros.remove(j);
				}
			}
		}
		if(requiredPros.size() == 0)
			return null;
		else
			return requiredPros.toString() + EXCEL_REQUIRED_COLUMN;
	}
	
	private String validateExcelData(List<String> contents,List<String> requiredPros) {
		int contLen = contents.size();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i < contLen; i++) {
			String row = contents.get(i);
			String[] values = row.split(ExcelHelper.SEPARATOR);
			if(StringUtils.isBlank(values[columnsIndex.get(USER_NAME)])){
				sb.append("第"+headRow+i+"行"+USER_NAME+"为空");
			}
			if(StringUtils.isBlank(values[columnsIndex.get(PASSWORD)])) {
				sb.append(","+PASSWORD+"为空");
			}
			sb.append(System.getProperty("line.separator"));
		}
		return sb.toString();
	}
	
	private List<String> acceptExcel() throws IOException {
		String savePath = getWebAppsRealPath() + "WORKDIR"+File.separator+"TEMP" + File.separator + fileInputFileName;
		StreamUtil.uploadActiveImgs(fileInput,savePath );
		File f = new File(savePath);
		List<String> contents = ExcelHelper.exportListFromExcel(f, sheetNo-1, headRow);
		f.delete();
		return contents;
	}

	public String impConsFromExcel() throws IOException {
		if (fileInput == null || (!fileInputFileName.endsWith(ExcelHelper.XLS)
				&& !fileInputFileName.endsWith(ExcelHelper.XLSX))) {
			jsonOut(EXCEL_NO_FILE);
			return null;
		}
		initParam();
		String savePath = getWebAppsRealPath() + "WORKDIR"+File.separator+"TEMP" + File.separator + fileInputFileName;
		StreamUtil.uploadActiveImgs(fileInput,savePath );
		File f = new File(savePath);
		List<String> contents = ExcelHelper.exportListFromExcel(f, sheetNo-1, headRow);
		f.delete();
		if (contents == null || contents.size() <= 0) {
			jsonOut(EXCEL_NO_DATA);
			return null;
		}
		if (contents != null && contents.size() >= 5000) {
			jsonOut(EXCEL_TOO_MUCH_DATA);
			return null;
		}
		String[] pros = contents.get(0).split(ExcelHelper.SEPARATOR);
		int[] mapping = getAttrMappingIndex(pros);
		if (checkInputParamErr(mapping))
			return null;
		contentService.saveContentsFromExcel(intCateId,pros,contents, getUserInfo(), mapping);
		jsonOut(EXCEL_IMP_SUCCESS + "共添加" + (contents.size() -1) + "条记录。");
		return null;
	}
	
	private boolean checkInputParamErr(int[] mapping) throws IOException{
		if (!StringUtils.isBlank(excelImpAttrMapping.getUniqueUserAttr()) && mapping[0] == -1) {
			jsonOut(EXCEL_NO_INPUT_ATTR + excelImpAttrMapping.getUniqueUserAttr());
			return true;
		}
		if (!StringUtils.isBlank(excelImpAttrMapping.getPassword()) && mapping[1] == -1) {
			jsonOut(EXCEL_NO_INPUT_ATTR + excelImpAttrMapping.getPassword());
			return true;
		}
		if (!StringUtils.isBlank(excelImpAttrMapping.getTitle()) && mapping[2] == -1) {
			jsonOut(EXCEL_NO_INPUT_ATTR + excelImpAttrMapping.getTitle());
			return true;
		}
		if (!StringUtils.isBlank(excelImpAttrMapping.getThumb()) && mapping[3] == -1) {
			jsonOut(EXCEL_NO_INPUT_ATTR + excelImpAttrMapping.getThumb());
			return true;
		}
		if (!StringUtils.isBlank(excelImpAttrMapping.getDescription()) && mapping[4] == -1) {
			jsonOut(EXCEL_NO_INPUT_ATTR + excelImpAttrMapping.getDescription());
			return true;
		}
		return false;
	}
	
	private void initParam() {
		if (sheetNo == null) {
			sheetNo = 1;
		}
		if (!StringUtils.isBlank(excelImpAttrMapping.getUniqueUserAttr())) {
			excelImpAttrMapping.setUniqueUserAttr(excelImpAttrMapping.getUniqueUserAttr().trim());
		}
	}
	
	private int[] getAttrMappingIndex(String[] pros) {
		int[] mapping = { -1, -1, -1, -1, -1 };
		for (int i = 1; i < pros.length; i++) {
			if (!StringUtils.isBlank(excelImpAttrMapping.getUniqueUserAttr())
					&& excelImpAttrMapping.getUniqueUserAttr().equals(pros[i].trim())) {
				mapping[0] = i;
			} 
			if (!StringUtils.isBlank(excelImpAttrMapping.getPassword())
					&& excelImpAttrMapping.getPassword().equals(pros[i].trim())) {
				mapping[1] = i;
			} 
			if (!StringUtils.isBlank(excelImpAttrMapping.getTitle())
					&& excelImpAttrMapping.getTitle().equals(pros[i].trim())) {
				mapping[2] = i;
			} 
			if (!StringUtils.isBlank(excelImpAttrMapping.getThumb())
					&& excelImpAttrMapping.getThumb().equals(pros[i].trim())) {
				mapping[3] = i;
			} 
			if (!StringUtils.isBlank(excelImpAttrMapping.getDescription())
					&& excelImpAttrMapping.getDescription().equals(pros[i].trim())) {
				mapping[4] = i;
			}
		}
		return mapping;
	}
}